﻿package pcenshao.commons.simpledb.mysql;

import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;

import pcenshao.commons.simpledb.BasicEntityManager;
import pcenshao.commons.simpledb.Entity;

/**
 * MySQL
 * 
 * @author pengyw
 * 
 */
public class MySQLEntityManager extends BasicEntityManager {

	public MySQLEntityManager() {
		super();
	}

	public MySQLEntityManager(DataSource dataSource, boolean lazyInit) {
		super(dataSource, lazyInit);
	}

	public MySQLEntityManager(DataSource dataSource) {
		super(dataSource);
	}

	private String orderByClause = null;

	public String getOrderByClause() {
		return orderByClause;
	}

	/**
	 * 设置order by子句,在调用queryRange(String,String[],String
	 * ,Object[],int,int)方法时将使用这个值<br>
	 * 设置为null,或者空白串,则忽略
	 * 
	 * @param orderByClause
	 */
	public void setOrderByClause(String orderByClause) {
		this.orderByClause = orderByClause;
	}

	@Override
	public List<Entity> queryRange(String tableName, String[] columns,
			String where, Object[] args, int offset, int limit) {
		if (tableName == null)
			throw new NullPointerException("tableName=null");
		if (columns == null) {
			columns = new String[] {};
		}

		StringBuilder buf = new StringBuilder();
		buf.append("select ");
		buf.append(" ");
		if (columns.length == 0) {
			buf.append(" * ");
		} else {
			for (String col : columns) {
				buf.append(col);
				buf.append(",");
			}
			buf.deleteCharAt(buf.length() - 1); // 删除最后的,
		}
		buf.append(" from ");
		buf.append(tableName);
		buf.append(" ");
		if (where != null && where.trim().length() > 0) { // where不为空的情况下添加
			buf.append(" where ");
			buf.append(where);
		}
		if(!StringUtils.isBlank(this.orderByClause)){
			
		}
		buf.append(" limit ");
		buf.append(offset);
		buf.append(",").append(limit);

		String sql = buf.toString();
		return queryList(sql, args);
	}

}
